#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<pthread.h>
#include<fcntl.h>
#include<errno.h>
#include<stdlib.h>
#include<time.h>
#include<semaphore.h>


#define BUFFER_SIZE 5

int buffer[BUFFER_SIZE];
sem_t empty;
sem_t full;

void* producer(void* arg) {
    int item = 0;
    while(1) {
        sem_wait(&empty);
        buffer[item % BUFFER_SIZE] = rand() % 500 + 1;
        printf("+++++: %d\n", buffer[item % BUFFER_SIZE]);
        item++;
        sem_post(&full);
        sleep(1);
    }
}

void* consumer(void* arg) {
    int item = 0;
    while(1) {
        sem_wait(&full);
        printf("-----: %d\n", buffer[item % BUFFER_SIZE]);
        item++;
        sem_post(&empty);
        sleep(3);
    }
    
}

int main(int argc, char* argv[])
{
    srand(time(NULL));
    sem_init(&empty, 0, BUFFER_SIZE);//设置初始值
    sem_init(&full, 0, 0);//设置初始值
    pthread_t tid1;
    pthread_t tid2;
    pthread_create(&tid1, NULL, producer, NULL);
    pthread_create(&tid2, NULL, consumer, NULL);
 
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);

    sem_destroy(&empty);//销毁
    sem_destroy(&full);
    return 0;
}
